package com.gdsdxy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdsdxy.dto.ResultVo;
import com.gdsdxy.dto.UserInfoDTO;
import com.gdsdxy.entity.UserInfo;
import com.gdsdxy.mapper.UserInfoMapper;
import com.gdsdxy.service.IUserInfoService;
import com.gdsdxy.utils.UserHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Resource
    UserInfoMapper userInfoMapper;

    @Override
    public ResultVo queryUserInfo() {
        // 1. 获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2. 获取用户信息
        UserInfo userInfo = getById(userId);
        // 3. 判断是否存在
        if (userInfo == null) {
            // 不存在，新建用户信息
            userInfo.setId(userId);
            userInfo.setUsername(UserHolder.getUser().getNickname());
            save(userInfo);
        }
        // 4. 返回用户信息
        return ResultVo.ok(userInfo);
    }
    @Override
    public ResultVo updateUserInfo(UserInfoDTO userInfoDTO) {
        // 1. 获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2. 将UserInfoDTO转换为UserInfo
        UserInfo userInfo = BeanUtil.copyProperties(userInfoDTO, UserInfo.class);
        // 3. 并设置用户id
        userInfo.setId(userId);
        // 4. 修改用户信息
        boolean result = updateById(userInfo);
        // 5. 返回信息
        return result ? ResultVo.ok() : ResultVo.fail("修改用户信息失败！");
    }

    @Override
    public ResultVo selectAllUserInfo(Integer page,Integer number) {
        Page<UserInfo> userInfoPage = new Page<>(page, number);
        userInfoMapper.selectPage(userInfoPage,null);
        return ResultVo.ok(userInfoPage);
    }

    @Override
    public ResultVo deleteUser(Long id) {
        boolean result = removeById(id);
        return result?ResultVo.ok("删除成功"):ResultVo.fail("删除失败");
    }
}
